/*
 * @Author: 皮卡丘
 * @Date: 2021-10-11 14:21:25
 * @LastEditors: 皮卡丘
 * @LastEditTime: 2021-10-11 18:42:24
 * @Description: 文件描述
 * @FilePath: /bamboo-backend/src/middleware/send/index.ts
 */
import Koa from 'koa';

const midSend = () => {
  const render =
    (ctx: Koa.Context) =>
    (data: any, code: number = 200, msg: string = '请求成功') => {
      ctx.set('Content-Type', 'application/json');
      ctx.body = {
        code,
        data,
        msg,
      };
    };

  const renderError =
    (ctx: Koa.Context) =>
    (data: any = {}, code: number = -200, msg: string = '请求错误') => {
      ctx.set('Content-Type', 'application/json');
      ctx.body = {
        code,
        data,
        msg,
      };
    };

  return async (ctx: Koa.Context, next: Koa.Next) => {
    ctx.send = render(ctx);
    ctx.sendError = renderError(ctx);
    await next();
  };
};

export default midSend;
